﻿using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using mqtttLib.Helper;

namespace Client
{
    /// <summary>
    /// <remarks>Xml序列化与反序列化</remarks>
    /// <creator>zhangdapeng</creator>
    /// </summary>
    public class XmlSerializeUtil
    {
         
        /// <summary>
        ///序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="serialObject"></param>
        /// <returns></returns>
        public static string Serializer<T>(T serialObject) where T : class
        {
            var emptyNamepsaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
            var serializer = new XmlSerializer(serialObject.GetType());
            var settings = new XmlWriterSettings
            {
                OmitXmlDeclaration = true,
                Encoding = Encoding.UTF8
            };
            using (var stream = new StringWriter())
            using (var writer = XmlWriter.Create(stream, settings))
            {
                serializer.Serialize(writer, serialObject, emptyNamepsaces);
                return stream.ToString();
            }
        }


        /// <summary>
        ///反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T Deserialize<T>(string xml) where T : class
        {
            using (var str = new StringReader(xml))
            {
                var xmlSerializer = new XmlSerializer(typeof(T));
                var result = (T)xmlSerializer.Deserialize(str);
                return result;
            }
        }
         

    }
}
